// 获取用户登录信息
async function getUserInfo() {
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      window.location.href = 'login.html';
      return;
    }

    const response = await fetch('/api/user/info', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });

    if (!response.ok) {
      const data = await response.json();
      throw new Error(data.message || '获取用户信息失败');
    }

    const data = await response.json();

    // 显示用户信息
    document.getElementById('username').textContent = data.user.username;
    document.getElementById('userRole').textContent = data.user.role === 'student' ? '学生' : '教师';

    // 如果有用户简介信息，显示相关信息
    if (data.user.profile) {
      if (data.user.profile.real_name) {
        document.getElementById('realName').textContent = data.user.profile.real_name;
      }

      if (data.user.profile.student_id) {
        document.getElementById('studentId').textContent = data.user.profile.student_id;
      }

      if (data.user.profile.department) {
        document.getElementById('department').textContent = data.user.profile.department;
      }

      if (data.user.profile.class_name) {
        document.getElementById('className').textContent = data.user.profile.class_name;
      }
    }

    return data.user;
  } catch (error) {
    console.error('获取用户信息失败:', error);
    // 如果是认证问题，重定向到登录页
    if (error.message.includes('令牌') || error.message.includes('认证')) {
      localStorage.removeItem('token');
      window.location.href = 'login.html';
    }
    return null;
  }
}

// 加载通知信息
// ... existing code ...

// 加载课表信息
// ... existing code ...

// 加载文档信息
// ... existing code ...

// 加载成绩信息
// ... existing code ...

// 加载消息信息
// ... existing code ...

// 初始化页面
document.addEventListener('DOMContentLoaded', async () => {
  // 获取用户信息
  const user = await getUserInfo();
  if (!user) return;

  // 初始化侧边栏激活状态
  document.querySelector('.nav-link[data-target="notifications"]').classList.add('active');
  document.getElementById('notificationsContent').classList.add('show');

  // 加载各模块数据
  loadNotifications();
  loadSchedule();
  loadDocuments();
  loadGrades();
  loadMessages();

  // 设置导航切换
  document.querySelectorAll('.nav-link').forEach(link => {
    link.addEventListener('click', function (e) {
      e.preventDefault();

      // 移除所有激活状态
      document.querySelectorAll('.nav-link').forEach(el => el.classList.remove('active'));
      document.querySelectorAll('.content-section').forEach(el => el.classList.remove('show'));

      // 设置当前项激活
      this.classList.add('active');
      const target = this.getAttribute('data-target');
      document.getElementById(`${target}Content`).classList.add('show');
    });
  });

  // 设置退出登录事件
  document.getElementById('logoutBtn').addEventListener('click', () => {
    localStorage.removeItem('token');
    window.location.href = 'login.html';
  });
}); 